package net.swa.system.web.action;

import java.util.List;

import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Required;
import org.apache.commons.lang.StringUtils;
import net.swa.system.beans.entity.Menu;
import net.swa.system.service.ICommonService;
import net.swa.system.service.IMenuService;
import net.swa.system.util.annotation.Log;

/**
 * 功能菜单action
 * 
 * 
 */
public class MenuAction extends AbstractBaseAction
{
	private static final long serialVersionUID = -3395155013072080770L;
	private ICommonService commonService;
	private IMenuService menuService;
	private Menu menu;

	/**
	 * 返回菜单列表页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Log(description = "菜单列表页面")
	public String listPage() throws Exception
	{
		return "list";
	}
	@Log(description = "查看功能菜单树")
	public String rootTree() throws Exception
	{
		String str = getRequestParameter("value");
		long roleId = 0;
		if (!StringUtils.isEmpty(str))
		{
			roleId = Long.parseLong(str);
		}
		List<Menu> rootList = menuService.getRootMenu(roleId);
		Menu root = new Menu();
		root.setTitle("功能菜单");
		root.setSubMenus(rootList);
		outString(root.toXml());
		return null;
	}
	/**
	 * 新建、编辑菜单操作
	 * 
	 * @return
	 * @throws Exception
	 */
	@Log(description = "编辑菜单")
	public String edit() throws Exception
	{
		if (menu != null && menu.getId() != 0)
		{// 编辑操作
			menu = commonService.commonFind(Menu.class, menu.getId());
		} else
		{// 新建操作
			menu = new Menu();
		}
		return "edit";
	}

	/**
	 * 菜单保存操作
	 * 
	 * @return
	 * @throws Exception
	 */
	@Log(description = "保存菜单")
	public String save() throws Exception
	{
		if (menu.getParent() != null && menu.getParent().getId() == 0)
		{
			menu.setParent(null);
		}
		if (menu.getId() == 0)
		{

			commonService.commonAdd(menu);
		} else
		{
			commonService.commonUpdate(menu);
		}
		outSuccess();
		return null;
	}
	@Log(description = "删除菜单")
	public String delete() throws Exception
	{
		List<Menu> subMenus = commonService.search("parent.id", menu.getId(), Menu.class);
		if (subMenus.size() > 0)
		{
			outError("该菜单下含有子菜单，请先删除子菜单！");
		} else
		{
			commonService.commonDelete("Menu", menu.getId());
			outSuccess();
		}
		return null;
	}
	// setter and getter

	public Menu getMenu()
	{
		return menu;
	}

	public void setMenu(Menu menu)
	{
		this.menu = menu;
	}

	public ICommonService getCommonService()
	{
		return commonService;
	}

	@Resource
	@Required
	public void setCommonService(ICommonService commonService)
	{
		this.commonService = commonService;
	}

	public IMenuService getMenuService()
	{
		return menuService;
	}
	@Resource
	@Required
	public void setMenuService(IMenuService menuService)
	{
		this.menuService = menuService;
	}
}
